import React, { useEffect, useRef, useState } from "react";
import { Button, message } from "antd";
import { useNavigate } from "react-router-dom";
import styles from "../css/map.module.css";
import back from "../assets/left.png";
import hourse3 from "../assets/hourse3.png";
import { fetchMapData, fetchLocationData } from "../api/mapApi"; // 引入封装好的接口
import { imgUrl } from '../config'; // 导入imgUrl
// 请替换为你自己有效的高德地图 API Key
const MAP_KEY = "2dbc93cbf59e66a1320227b3ca416b28";
// 请替换为你自己有效的安全密钥
const SECURITY_JS_CODE = "ccc2f6385595eb1fdda9a2370ab3995a";

const ScenicMap = () => {
    const navigate = useNavigate();
    const startLat = 35.292083;
    const startLng = 113.921914;

    const mapContainerRef = useRef(null);
    const [mapLoaded, setMapLoaded] = useState(false);
    const [pendingScenicId, setPendingScenicId] = useState(null);
    const mapRef = useRef(null);
    const drivingRef = useRef(null);
    const startMarkerRef = useRef(null);
    const endMarkerRef = useRef(null);
    const [address, setAddress] = useState("");
    const [array, setArray] = useState([]);
    const [currentPosition, setCurrentPosition] = useState([startLng, startLat]);
    const [selectedId, setSelectedId] = useState(null);
    const [showOptions, setShowOptions] = useState(false);

    useEffect(() => {
        window._AMapSecurityConfig = { securityJsCode: SECURITY_JS_CODE };

        const initAMap = () => {
            if (window.AMap) {
                initMap();
            } else {
                const existingScript = document.querySelector(`script[src="https://webapi.amap.com/maps?v=1.4.15&key=${MAP_KEY}"]`);
                if (existingScript) {
                    existingScript.onload = () => initMap();
                    existingScript.onerror = () => {
                        message.error("高德地图 API 加载失败");
                    };
                } else {
                    const script = document.createElement("script");
                    script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${MAP_KEY}`;
                    script.async = true;
                    script.onload = () => initMap();
                    script.onerror = () => {
                        message.error("高德地图 API 加载失败");
                    };
                    document.body.appendChild(script);
                }
            }
        };

        initAMap();

        return () => {
            if (mapRef.current) {
                mapRef.current.destroy();
                mapRef.current = null;
            }
            const scripts = document.querySelectorAll('script[src*="amap.com"]');
            scripts.forEach(script => document.body.removeChild(script));
        };
    }, []);

    useEffect(() => {
        if (mapLoaded) {
            fetchData();
        }
    }, [mapLoaded]);

    useEffect(() => {
        if (mapLoaded && pendingScenicId !== null) {
            handleItemClick(0, pendingScenicId);
            setPendingScenicId(null);
        }
    }, [mapLoaded, pendingScenicId]);

    const initMap = () => {
        if (!mapContainerRef.current) return;

        const map = new window.AMap.Map(mapContainerRef.current, {
            zoom: 13,
            center: [startLng, startLat],
            resizeEnable: true
        });
        mapRef.current = map;

        window.AMap.plugin(["AMap.Driving", "AMap.Geocoder"], (err) => {
            if (err) {
                message.error("高德地图插件加载失败");
                return;
            }

            drivingRef.current = new window.AMap.Driving({
                map: mapRef.current,
                policy: window.AMap.DrivingPolicy.LEAST_TIME,
                showTraffic: true,
                polylineOptions: {
                    strokeColor: "#1890ff",
                    strokeWeight: 6,
                    strokeOpacity: 0.8
                }
            });

            createMarker([startLng, startLat], "start");
            setMapLoaded(true);
        });
    };

const fetchData = async () => {
  try {
    const response = await fetchMapData(3);
    if (response.data) {  // 直接使用 response.data
      setArray(response.data);
      if (response.data.length > 0) {
        if (mapLoaded) {
          handleItemClick(0, response.data[0].id);
        } else {
          setPendingScenicId(response.data[0].id);
        }
      }
    }
  } catch (error) {
    console.error("获取景点数据失败:", error);
    message.error("获取景点数据失败");
  }
};
 const fetchLocationDataById = async (id) => {
  try {
    const response = await fetchLocationData(id);
    if (response.data?.[0]) {  // 直接使用 response.data
      const { lng, lat } = response.data[0];
      if (lng && lat) {
        setCurrentPosition([lng, lat]);
        return [lng, lat];
      }
    }
    return null;
  } catch (error) {
    message.error("获取位置数据失败");
    return null;
  }
};

    const handleItemClick = async (index, id) => {
        if (!mapLoaded || !drivingRef.current) {
            message.error("地图或插件未加载完成，请稍后再试");
            return;
        }
        setSelectedId(id);
        const position = await fetchLocationDataById(id);
        if (position) {
            planRoute([startLng, startLat], position);
        }
    };

    const planRoute = (start, end) => {
        if (!mapRef.current || !drivingRef.current) {
            message.error("地图未初始化完成");
            return;
        }

        if (!isValidCoordinates(start) || !isValidCoordinates(end)) {
            message.error("经纬度无效");
            return;
        }

        startMarkerRef.current?.setMap(null);
        endMarkerRef.current?.setMap(null);

        createMarker(start, "start");
        createMarker(end, "end");
        mapRef.current.setFitView();

        drivingRef.current.search(start, end, (status, result) => {
            if (status === "complete") {
                message.success("路线规划完成");
            } else {
                message.error("路线规划失败");
                window.location.reload();
            }
        });
    };

    const createMarker = (position, type) => {
        const marker = new window.AMap.Marker({
            position,
            map: mapRef.current,
            icon: new window.AMap.Icon({
                size: new window.AMap.Size(20, 36),
                image: type === "start"
                    ? "https://webapi.amap.com/theme/v1.3/markers/n/start.png"
                    : "https://webapi.amap.com/theme/v1.3/markers/n/end.png",
                imageSize: new window.AMap.Size(20, 36)
            }),
            offset: new window.AMap.Pixel(-10, -36)
        });

        if (type === "start") {
            startMarkerRef.current = marker;
        } else {
            endMarkerRef.current = marker;
        }
    };

    const isValidCoordinates = (coords) => {
        return Array.isArray(coords) && coords.length === 2 &&
            !isNaN(coords[0]) && !isNaN(coords[1]);
    };

    const renderItems = () => {
        return array.map((item, index) => (
            <div
                key={item.id}
                className={`${styles.items} ${selectedId === item.id ? styles.selected : ''}`}
                onClick={() => handleItemClick(index, item.id)}
            >
                <p>{item.name}</p>
            </div>
        ));
    };

    const renderMapContent = () => {
        return array.map((item) => (
            <div key={item.id} className={styles.mapItem}>
                <img src={`${imgUrl}${item.img}`} alt={item.name} />
                <p>{item.name}</p>
            </div>
        ));
    };

    const handleGoBack = () => navigate(-1);
    const handleGoHome = () => navigate("/home");
    const handleGoToFood = () => navigate("/deliciousFood");

    return (
        <div className={styles.scenicMapContainer}>
            <div className={styles.hintBig}>
                <div className={styles.hint}>
                    <div className={styles.hintOne}>该浏览器不支持规划路线！</div>
                </div>
            </div>
            <div className={styles.topContainer}>
                <div className={styles.top}>
                    <div className={styles.left}>
                        <img className={styles.topimg} src={back} alt="返回" onClick={handleGoBack} />
                        <div className={styles.line}></div>
                        <img className={styles.hourse} src={hourse3} alt="首页" onClick={handleGoHome} />
                    </div>
                    <span className={styles.text}>{address || "景区地图"}</span>
                </div>
                <div className={styles.optionContainer}>
                    <div className={styles.optionCard}>
                        <div className={styles.options}>
                            <div className={styles.optionOne}>{renderItems()}</div>
                        </div>
                        <div className={styles.optionsDiv}></div>
                    </div>
                </div>
                {showOptions && (
                    <div className={styles.optionImg}>
                        <div className={styles.imgTop}>
                            <span>全部</span>
                            <img
                                onClick={() => setShowOptions(false)}
                                src="./img/caher.png"
                                alt="关闭"
                            />
                        </div>
                        <div className={styles.four}>{renderMapContent()}</div>
                    </div>
                )}
            </div>
            <div
                ref={mapContainerRef}
                className={styles.mapContainer}
                style={{
                    width: "100vh",
                    height: "calc(100vh - 120px)",
                    position: "absolute",
                    top: "85px",
                    left: 0,
                    border: "1px solid #ddd"
                }}
            ></div>
            <div className={styles.address}>{address}</div>
        </div>
    );
};

export default ScenicMap;